package com.leilei.gateway.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leilei.gateway.entity.Result;
import com.leilei.gateway.entity.po.AccessUser;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * @author lei
 * @create 2022-04-07 17:19
 * @desc 权限过滤器
 **/
@Component
@Log4j2
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    Set<String> whiteList = new HashSet<String>() {
        {
            add("/app-base-center/nacos/discovery");
        }
    };

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (whiteList.contains(path)) {
            //当前放行,交由下个过滤器过滤
            return chain.filter(exchange);
        }
        HttpHeaders httpHeaders = request.getHeaders();
        String token = httpHeaders.getFirst("x-request-token");
        //按业务验证对比token
        if (token == null || token.replace(" ","").length() < 1) {
            byte[] bytes = JSON.toJSONString(new Result<>(-1, "无权限查看此接口!", null), SerializerFeature.WriteMapNullValue)
                    .getBytes(StandardCharsets.UTF_8);
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            //响应出去
            return response.writeWith(Flux.just(buffer));
        }
        ServerHttpRequest.Builder requestBuilder = request.mutate();
        // 模拟jwt解析用户数据,再次填充至请求头
        requestBuilder.header("access-user", JSON.toJSONString(new AccessUser(UUID.randomUUID().toString(), 12)));
        ServerHttpRequest newRequest = requestBuilder.build();
        exchange.mutate().request(request).build();
        ServerWebExchange webExchange = exchange.mutate().request(newRequest).build();
        log.info("\n");
        log.info("当前请求url:{},请求方式:{}", webExchange.getRequest().getURI().toString(), webExchange.getRequest().getMethod());
        log.info("\n");
        //当前放行,交由下个过滤器过滤
        return chain.filter(webExchange);
    }

    @Override
    public int getOrder() {
        return -10;
    }
}
